package com.midou.administration.utils;

import com.sun.jersey.client.impl.CopyOnWriteHashMap;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;


@Component
@ServerEndpoint("/websocket/{userId}/{distinguish}")
public class WebSocketServlet {

    //记录链接数
    private static int onlineCount = 0;
    private static CopyOnWriteHashMap<Integer,WebSocketServlet> webSocketMap = new CopyOnWriteHashMap<>();
    //唯一会话
    private Session session;

    private Integer userId;

    /**
     * 连接成功
     * @param session
     * @param userId
     *
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId")Integer userId,@PathParam("distinguish")Integer distinguish){
        this.session = session;
        this.userId = userId;
        System.out.println(userId+"\t"+session);
        if (!(distinguish>0)){
            webSocketMap.put(userId,this);
        }else{
            addOnlineCount();
        }
        System.out.println("新连接加入，当前已定桌数："+ getOnlineCount()+"\t"+session.getId());
    }

    /**
     * 连接关闭
     */
    @OnClose
    public void onClose(@PathParam("distinguish")Integer distinguish){
        webSocketMap.remove(this);
        if (distinguish>0){
            subOnlineCount();
        }
        System.out.println("连接关闭，当前顾客人数："+getOnlineCount());
    }

    /**
     * 接收客户端消息
     */
    @OnMessage
    public void onMessage(String message,Session session){
        System.out.println("客户端消息："+message);
        try {
            webSocketMap.get(userId).sendMessage(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发生错误调用
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session,Throwable error){
        System.out.println("websocket发生错误");
        error.printStackTrace();
    }

    /**
     * 发送消息
     * @param message
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 获取在线数
     * @return
     */
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }
    public static synchronized void addOnlineCount() {
        WebSocketServlet.onlineCount++;
    }
    public static synchronized void subOnlineCount() {
        WebSocketServlet.onlineCount--;
    }
}
